package org.convallaria.framework.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 匿名访问路径注册表
 * 用于动态管理匿名访问路径
 * 
 * @author convallaria
 * @since 1.0.0
 */
@Slf4j
@Component
public class AnonymousPathRegistry {

    private final List<String> dynamicAnonymousPaths = new CopyOnWriteArrayList<>();
    
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 注册动态匿名访问路径
     * 
     * @param path 路径
     */
    public void registerAnonymousPath(String path) {
        if (path != null && !path.trim().isEmpty()) {
            dynamicAnonymousPaths.add(path);
            log.info("注册动态匿名访问路径: {}", path);
        }
    }

    /**
     * 注销动态匿名访问路径
     * 
     * @param path 路径
     */
    public void unregisterAnonymousPath(String path) {
        if (dynamicAnonymousPaths.remove(path)) {
            log.info("注销动态匿名访问路径: {}", path);
        }
    }

    /**
     * 获取所有匿名访问路径（静态配置 + 动态注册）
     * 
     * @return 匿名访问路径列表
     */
    public List<String> getAllAnonymousPaths() {
        List<String> allPaths = new ArrayList<>();
        
        // 添加静态配置的路径
        allPaths.addAll(securityProperties.getWhiteList());
        
        // 添加动态注册的路径
        allPaths.addAll(dynamicAnonymousPaths);
        
        return allPaths;
    }

    /**
     * 检查路径是否为匿名访问路径
     * 
     * @param requestURI 请求URI
     * @return 是否为匿名访问路径
     */
    public boolean isAnonymousPath(String requestURI) {
        List<String> allPaths = getAllAnonymousPaths();
        
        for (String path : allPaths) {
            if (path.endsWith("/**")) {
                // 通配符匹配
                String prefix = path.substring(0, path.length() - 3);
                if (requestURI.startsWith(prefix)) {
                    return true;
                }
            } else if (path.equals(requestURI)) {
                // 精确匹配
                return true;
            }
        }
        
        return false;
    }

    /**
     * 清空动态注册的路径
     */
    public void clearDynamicPaths() {
        dynamicAnonymousPaths.clear();
        log.info("清空所有动态匿名访问路径");
    }

    /**
     * 获取动态注册的路径数量
     * 
     * @return 动态路径数量
     */
    public int getDynamicPathCount() {
        return dynamicAnonymousPaths.size();
    }
}
